﻿using System;
using System.ComponentModel;
using XCI.Core;
using XCI.Extensions;
using XCI.Helper;

namespace XCI.Windows.Controls
{
    public partial class GridPager : BaseUserControl
    {
        private int _totalPage;
        private int _totalCount;
        private string _pageSizeList;

        /// <summary>
        /// 分页控件每页数量,默认:20
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public static int DefaultPageSize { get; set; } = 20;

        /// <summary>
        /// 分页控件每页数量快捷选择,多个用逗号隔开
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public static string DefaultPageSizeList { get; set; } = "10,20,50,100,200";

        /// <summary>
        /// 每页大小
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int PageSize
        {
            get
            {
                if (barPageSize.EditValue == null)
                {
                    barPageSize.EditValueChanged -= barPageSize_EditValueChanged;
                    barPageSize.EditValue = DefaultPageSize.ToString();
                    barPageSize.EditValueChanged += barPageSize_EditValueChanged;
                }
                return barPageSize.EditValue.ToInt();
            }
            set
            {
                barPageSize.EditValueChanged -= barPageSize_EditValueChanged;
                barPageSize.EditValue = value.ToString();
                barPageSize.EditValueChanged += barPageSize_EditValueChanged;
            }
        }

        /// <summary>
        /// 分页大小下拉列表
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string PageSizeList
        {
            get => _pageSizeList;
            set
            {
                _pageSizeList = value;
                FillPageSizeList(value);
            }
        }

        /// <summary>
        /// 刷新按钮延迟时间(毫秒)
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int RefreshDelay { get; set; } = 5000;

        /// <summary>
        /// 页数,从1开始
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int PageIndex { get; set; } = 1;

        /// <summary>
        /// 总记录数
        /// </summary>
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public int TotalCount
        {
            get => _totalCount;
            set
            {
                _totalCount = value;
                this.BindInfo();
            }
        }

        [Category("XCI")]
        [Description("页面发生变化时触发")]
        public event EventHandler<PagerEventArgs> PageChanged;

        public GridPager()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!DesignMode)
            {
                this.barController1.AppearancesBar.Dock.BackColor = this.BackColor;
                this.barController1.AppearancesBar.Dock.Options.UseBackColor = true;
                this.bar1.OptionsBar.UseWholeRow = true;

                //填充分页大小下拉列表
                FillPageSizeList(DefaultPageSizeList);

                barPageSize.Enabled = false;
                barGoPage.Enabled = false;
                barFirstPage.Enabled = false;
                barLastPage.Enabled = false;
                barPreviousPage.Enabled = false;
                barNextPage.Enabled = false;
                barRefresh.Enabled = false;
                barSummaryInfo.Caption = string.Empty;

                this.barPageSize.EditValueChanged += barPageSize_EditValueChanged;
                this.barGoPage.EditValueChanged += barGoPage_EditValueChanged;

                this.barFirstPage.ItemClick += barFirstPage_ItemClick;
                this.barPreviousPage.ItemClick += barPreviousPage_ItemClick;
                this.barNextPage.ItemClick += barNextPage_ItemClick;
                this.barLastPage.ItemClick += barLastPage_ItemClick;
                this.barRefresh.ItemClick += barRefresh_ItemClick;
            }
        }

        private void FillPageSizeList(string pageSizeList)
        {
            if (!string.IsNullOrEmpty(pageSizeList))
            {
                this.repositoryItemComboBox1.Items.BeginUpdate();
                this.repositoryItemComboBox1.Items.Clear();
                var sz = pageSizeList.SplitToArray();
                foreach (var item in sz)
                {
                    this.repositoryItemComboBox1.Items.Add(item);
                }
                this.repositoryItemComboBox1.Items.EndUpdate();
            }
        }

        private void BindInfo()
        {
            PageIndex = FixPageIndex(PageIndex);

            var pageInfo = new PageInfo(PageIndex, PageSize, TotalCount);
            _totalPage = pageInfo.TotalPages;

            barTotalPage.Caption = $"共{pageInfo.TotalPages}页";
            barSummaryInfo.Caption = $"显示{pageInfo.RecordStartIndex}到{pageInfo.RecordEndIndex},共{pageInfo.TotalCount}条记录";

            barGoPage.EditValueChanged -= barGoPage_EditValueChanged;
            barGoPage.EditValue = pageInfo.PageIndex;
            barGoPage.EditValueChanged += barGoPage_EditValueChanged;

            barPageSize.Enabled = pageInfo.HasData;
            barGoPage.Enabled = pageInfo.HasData;

            barFirstPage.Enabled = pageInfo.HasData && !pageInfo.IsFirst;
            barLastPage.Enabled = pageInfo.HasData && !pageInfo.IsLast;
            barPreviousPage.Enabled = pageInfo.HasData && pageInfo.HasPreviousPage;
            barNextPage.Enabled = pageInfo.HasData && pageInfo.HasNextPage;


            TimerHelper.DelayExecuteWin(RefreshDelay, () => barRefresh.Enabled = pageInfo.HasData);
        }

        public void GotoPage(int index)
        {
            PageIndex = FixPageIndex(index);
            PagerEventArgs args = new PagerEventArgs { PageIndex = PageIndex, PageSize = PageSize };
            PageChanged?.Invoke(this, args);
        }

        public void SetPageIndex(int? pageIndex)
        {
            if (pageIndex.HasValue)
            {
                PageIndex = pageIndex.Value;
            }
        }

        private int FixPageIndex(int pageIndex)
        {
            if (pageIndex <= 0) pageIndex = 1;
            if (_totalPage > 0 && pageIndex > _totalPage) pageIndex = _totalPage;
            return pageIndex;
        }

        private void barPageSize_EditValueChanged(object sender, EventArgs e)
        {
            var pageInfo = new PageInfo(1, PageSize, TotalCount);
            _totalPage = pageInfo.TotalPages;
            GotoPage(1);
        }

        private void barGoPage_EditValueChanged(object sender, EventArgs e)
        {
            GotoPage(barGoPage.EditValue.ToInt());
        }

        private void barRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            barRefresh.Enabled = false;
            GotoPage(PageIndex);
        }

        private void barFirstPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            GotoPage(1);
        }

        private void barPreviousPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            GotoPage(PageIndex - 1);
        }

        private void barNextPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            GotoPage(PageIndex + 1);
        }

        private void barLastPage_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            GotoPage(_totalPage);
        }
    }
}
